package com.aviccxzx.smarthome.UserModule;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aviccxzx.smarthome.CommonModule.GosBaseActivity;
import com.aviccxzx.smarthome.CommonModule.GosDeploy;
import com.aviccxzx.smarthome.DeviceModule.GosDeviceListActivity;
import com.aviccxzx.smarthome.GosApplication;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.PushModule.GosPushManager;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.ThirdAccountModule.BaseUiListener;
import com.aviccxzx.smarthome.base.GosUserModuleBaseActivity;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.entity.LoginData;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizThirdAccountType;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.isSubed;

@SuppressLint("HandlerLeak")
public class GosUserLoginActivity extends GosUserModuleBaseActivity implements
        OnClickListener {

    GosPushManager gosPushManager;

    /**
     * The et Name
     */
    private static EditText etName;

    /**
     * The et Psw
     */
    private static EditText etPsw;

    /**
     * The btn Login
     */
    private Button btnLogin;

    /**
     * The tv Register
     */
    private TextView tvRegister;

    /**
     * The tv Forget
     */
    private TextView tvForget;


    /**
     * The cb Laws
     */
    private CheckBox cbLaws;

    //	/** The ll QQ */
    //	private LinearLayout llQQ;
    //
    //	/** The ll Wechat */
    //	private LinearLayout llWechat;
    //
    /**
     * The Tencent
     */
    private Tencent mTencent;

    /**
     * The Wechat
     */
    public static IWXAPI mIwxapi;
    ImageView QQ_img, weichat_img;

    /**
     * The Scope
     */
    private String Scope = "get_user_info,add_t";

    /**
     * The IUiListener
     */
    IUiListener listener;

    Intent intent;

    /**
     * The GizThirdAccountType
     */
    public static GizThirdAccountType gizThirdAccountType;

    /**
     * The THRED_LOGIN UID&TOKEN
     */
    public static String thirdUid, thirdToken;

    public static enum handler_key {

        /**
         * 登录
         */
        LOGIN,

        /**
         * 自动登录
         */
        AUTO_LOGIN,

        /**
         * 第三方登录
         */
        THRED_LOGIN,

    }

    /**
     * 与WXEntryActivity共用Handler
     */
    private Handler baseHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            handler_key key = handler_key.values()[msg.what];
            switch (key) {
                // 登录
                case LOGIN:
                    String phonematch = "[0-9]{11}";
                    String name = etName.getText().toString().trim();
                    String pwd = etPsw.getText().toString().trim();
                    if (name.matches(phonematch)) {
                        progressDialog.show();
                        GosDeviceListActivity.loginStatus = 0;

                        GizWifiSDK.sharedInstance().userLogin(
                                name,
                                pwd);
                    } else {
                        showToast("请输入正确的手机号");
                    }

                    break;
                // 自动登录
                case AUTO_LOGIN:
                    progressDialog.show();
                    GosDeviceListActivity.loginStatus = 0;
                    GizWifiSDK.sharedInstance().userLogin(
                            spf.getString("UserName", ""),
                            spf.getString("PassWord", ""));
                    break;
                // 第三方登录
                case THRED_LOGIN:
                    progressDialog.show();
                    GosDeviceListActivity.loginStatus = 0;
                    GizWifiSDK.sharedInstance().loginWithThirdAccount(
                            gizThirdAccountType, thirdUid, thirdToken);

                    spf.edit().putString("thirdUid", thirdUid).commit();
                    spf.edit().putString("UserName", "").commit();
                    spf.edit().putString("PassWord", "").commit();

                    isclean = true;
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.AppTheme);
        if (!this.isTaskRoot()) {// 判断此activity是不是任务控件的源Activity，“非”也就是说是被系统重新实例化出来的
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
                    && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        if (GosApplication.flag != 0) {
            GosBaseActivity.noIDAlert(this, R.string.AppID_Toast);
        }

        // 在配置文件中选择推送类型（0：不开启推送，1：极光推送，2：百度推送。默认为0）
        gosPushManager = new GosPushManager(GosDeploy.setPushType(), this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.login_lay_v19);
        }
        // 设置actionBar
        //		setActionBar(false, false, R.string.app_company);
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        JPushInterface.onResume(this);
        if (isclean) {
            etName.setText("");
            etPsw.setText("");
            isclean = false;

        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    private void initView() {
        etName = (EditText) findViewById(R.id.editText_login_phone_number);
        etPsw = (EditText) findViewById(R.id.editText_login_pass_word);

        btnLogin = (Button) findViewById(R.id.login_tv);
        tvRegister = (TextView) findViewById(R.id.regist_tv);
        tvForget = (TextView) findViewById(R.id.forget_pwd_tv);
        cbLaws = (CheckBox) findViewById(R.id.cbLaws);
        QQ_img = (ImageView) findViewById(R.id.QQ_img);
        weichat_img = (ImageView) findViewById(R.id.weichat_img);

        String name = spf.getString("UserName", "");
        String paw = spf.getString("PassWord", "");
        if (!TextUtils.isEmpty(name)) {
            etName.setText(name);
        }
        if (!TextUtils.isEmpty(paw)) {
            etPsw.setText(paw);
        }
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(paw)) {
            baseHandler.sendEmptyMessage(handler_key.LOGIN.ordinal());
        }
    }


    private void initEvent() {
        btnLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvForget.setOnClickListener(this);
        QQ_img.setOnClickListener(this);
        weichat_img.setOnClickListener(this);

        //		llQQ.setOnClickListener(this);
        //		llWechat.setOnClickListener(this);

        cbLaws.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                String psw = etPsw.getText().toString();

                if (isChecked) {
                    etPsw.setInputType(0x90);
                } else {
                    etPsw.setInputType(0x81);
                }
                etPsw.setSelection(psw.length());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_tv:
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    Toast.makeText(GosUserLoginActivity.this,
                            R.string.toast_name_wrong, Toast.LENGTH_LONG).show();
                    return;
                }
                if (TextUtils.isEmpty(etPsw.getText().toString())) {
                    Toast.makeText(GosUserLoginActivity.this,
                            R.string.toast_psw_wrong, Toast.LENGTH_LONG).show();
                    return;
                }
                baseHandler.sendEmptyMessage(handler_key.LOGIN.ordinal());
                break;

            case R.id.regist_tv:
                intent = new Intent(GosUserLoginActivity.this,
                        GosRegisterUserActivity.class);
                startActivity(intent);
                break;
            case R.id.forget_pwd_tv:
                intent = new Intent(GosUserLoginActivity.this,
                        GosForgetPasswordActivity.class);
                startActivity(intent);
                break;

            case R.id.QQ_img:
                String tencentAPPID = GosDeploy.setTencentAppID();
                if (TextUtils.isEmpty(tencentAPPID)
                        || tencentAPPID.contains("your_tencent_app_id")) {
                    noIDAlert(this, R.string.TencentAPPID_Toast);
                    return;
                } else {
                    // 启动QQ登录SDK
                    mTencent = Tencent.createInstance(GosDeploy.setTencentAppID(),
                            this.getApplicationContext());
                }

                listener = new BaseUiListener() {
                    protected void doComplete(JSONObject values) {
                        Message msg = new Message();
                        try {
                            if (values.getInt("ret") == 0) {
                                gizThirdAccountType = GizThirdAccountType.GizThirdQQ;
                                thirdUid = values.getString("openid").toString();
                                thirdToken = values.getString("access_token")
                                        .toString();
                                msg.what = handler_key.THRED_LOGIN.ordinal();
                                baseHandler.sendMessage(msg);
                            } else {
                                Toast.makeText(GosUserLoginActivity.this,
                                        msg.obj.toString(), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                mTencent.login(this, Scope, listener);
                break;
            case R.id.weichat_img:
                String wechatAppID = GosDeploy.setWechatAppID();
                String wechatAppSecret = GosDeploy.setWechatAppSecret();
                if (TextUtils.isEmpty(wechatAppID)
                        || TextUtils.isEmpty(wechatAppSecret)
                        || wechatAppID.contains("your_wechat_app_id")
                        || wechatAppSecret.contains("your_wechat_app_secret")) {
                    noIDAlert(this, R.string.WechatAppID_Toast);
                    return;
                } else {

                    // 设置与WXEntryActivity共用Handler
                    setBaseHandler(baseHandler);

                    // 启动微信登录SDK
                    mIwxapi = WXAPIFactory.createWXAPI(this, wechatAppID, true);

                    // 将应用的AppID注册到微信
                    mIwxapi.registerApp(wechatAppID);
                }

                if (!(mIwxapi.isWXAppInstalled() && mIwxapi.isWXAppSupportAPI())) {
                    noIDAlert(this, R.string.No_WXApp);
                    return;
                }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                mIwxapi.sendReq(req);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, listener);
    }

    /**
     * 设置云端服务回调
     */
    protected void didGetCurrentCloudService(
            GizWifiErrorCode result,
            java.util.concurrent.ConcurrentHashMap<String, String> cloudServiceInfo) {
        if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {
            Toast.makeText(this, toastError(result), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 用户登录回调
     */
    @Override
    protected void didUserLogin(GizWifiErrorCode result, String uid,
                                String token) {
        progressDialog.cancel();
        Log.i("Apptest", GosDeviceListActivity.loginStatus + "\t" + "User");
        if (GosDeviceListActivity.loginStatus == 4
                || GosDeviceListActivity.loginStatus == 3) {
            return;
        }
        Log.i("Apptest", GosDeviceListActivity.loginStatus + "\t" + "UserLogin");

        if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {// 登录失败
            Toast.makeText(GosUserLoginActivity.this, toastError(result),
                    Toast.LENGTH_LONG).show();

        } else {// 登录成功

            GosDeviceListActivity.loginStatus = 1;
            Toast.makeText(GosUserLoginActivity.this,
                    R.string.toast_login_successful, Toast.LENGTH_LONG).show();

            // TODO 绑定推送
            GosPushManager.pushBindService(token);
            if (JPushInterface.isPushStopped(getApplicationContext())){
                //如果推送服务stoped
                JPushInterface.resumePush(getApplicationContext());
            }

            if (!TextUtils.isEmpty(etName.getText().toString())
                    && !TextUtils.isEmpty(etPsw.getText().toString())
                    && !isclean) {
                spf.edit().putString("UserName", etName.getText().toString())
                        .commit();
                spf.edit().putString("PassWord", etPsw.getText().toString())
                        .commit();
            }
            spf.edit().putString("Uid", uid).commit();
            spf.edit().putString("Token", token).commit();


            RetrofitService service = RetrofitHelper.getInstance(this).getLoginServer();
            Gson gson = new Gson();

            //            HashMap<String, String> paramsMap = new HashMap<>();

            //			{
            //				"appSecret": "string",
            //					"appid": "string",
            //					"expire_at": "2017-04-25T00:59:31.086Z",
            //					"token": "string",
            //					"uid": "string"
            //			}
            LoginData data = new LoginData();
            data.setAppSecret(MsgID.APP_SECRET);
            data.setAppid(MsgID.APPID);
            data.setExpire_at(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
            data.setToken(token);
            data.setUid(uid);

            String strEntity = gson.toJson(data);

            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
            Call<FeedBack> call = service.login(body);

            call.enqueue(new Callback<FeedBack>() {
                @Override
                public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                    if (response.body() != null && response.body().getData() != null)
                        if (!TextUtils.isEmpty(response.body().getData().toString())) {
                            spf.edit().putString("loginToken", response.body().getData().toString()).commit();
                            sendTel();
                        }
                }

                @Override
                public void onFailure(Call<FeedBack> call, Throwable t) {
                }
            });
            intent = new Intent(GosUserLoginActivity.this,
                    MainAct.class);
            startActivity(intent);
            isSubed = false;
            GosUserLoginActivity.this.finish();
        }
    }

    public void sendTel() {
        RetrofitService service = RetrofitHelper.getInstance(GosUserLoginActivity.this).getServer();
        Call<FeedBack> call = service.update("", "", "", etName.getText().toString());
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                response.toString();
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {
            }
        });
    }

    /**
     * 解绑推送回调
     *
     * @param result
     */
    protected void didChannelIDUnBind(GizWifiErrorCode result) {
        if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {
            Toast.makeText(this, toastError(result), Toast.LENGTH_LONG).show();
        }

        Log.i("Apptest", "UnBind:" + result.toString());
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); // 调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            String doubleClick = (String) getText(R.string.double_click);
            Toast.makeText(this, doubleClick, Toast.LENGTH_LONG).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            this.finish();
            System.exit(0);
        }
    }

}
